import { Component, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppModalComponentBase } from '@shared/common/app-modal-component-base';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { JsonEditorComponent, JsonEditorOptions } from './json-editor.component';

export interface IJsonEditorModalOptions {
    message: string;
    data: any;
    schema: any;
}
export interface IJsonEditorModalCallbackData {
    message: string;
    data: string;
}

@Component({
    selector: 'json-editor-modal',
    templateUrl: './json-editor-modal.component.html'
})
export class JsonEditorModalComponent  extends AppModalComponentBase{

    @ViewChild('modal', { static: true }) modal: ModalDirective;
    @ViewChild('editor', { static: false }) editor: JsonEditorComponent;

    @Output() callback: EventEmitter<IJsonEditorModalCallbackData> = new EventEmitter<IJsonEditorModalCallbackData>();

    editorOptions: JsonEditorOptions;
    data: any;

    saving = false;

    formEdit = false;

    private options: IJsonEditorModalOptions;

    constructor(
        injector: Injector,
    ) {
        super(injector);
        this.editorOptions = new JsonEditorOptions();
        this.editorOptions.modes = ['text','code', 'tree', 'view']; 
        this.editorOptions.mode = 'text';
        this.editorOptions.expandAll = true;
    }


    configure(options: IJsonEditorModalOptions): void {
        this.options = options;

        this.data = options.data;
        this.editor.data = this.data;

        this.editorOptions.schema = options.schema;
        this.editor.setSchema(options.schema,{});
    }

    show() {
        if (!this.options) {
            throw Error('Should call FileFinderModalComponent.configure once before FileFinderModalComponent.show!');
        }
        this.formEdit = false;
        this.modal.show();
    }

    close(): void {
        this.modal.hide();
    }

    save() { 
        this.callback.emit({message:this.options.message, data: JSON.stringify(this.data, null, 4)});
        this.close();
    }
}
